﻿using System;
using System.Configuration;
using System.Data.SqlClient;

namespace ThirdPrize.Classes
{
    public sealed class ComicEdit : IDisposable
    {
        public string UserId { get; set; }
        public string Votes { get; set; }

        private readonly SqlConnection _myConn = new SqlConnection();

        public void Dispose()
        {
            _myConn.Dispose();
            _myConn.Close();
        }

        public ComicEdit()
        {
            _myConn.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            _myConn.Open();
        }

        public bool AddOrUpdate(int comicNo, int noPanels, string title, string comment, string altText, int imageType, DateTime publishDate)
        {
            bool result = false;

            try
            {
                if (Delete(comicNo))
	            {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        string sql = "insert into Comics ";
                        sql += "values(@comicNo, @noPanels, @title, @publishDate, @comment, @imageType, @altText)";
                        cmd.CommandText = sql;
                        cmd.Parameters.AddWithValue("@comicNo", comicNo);
                        cmd.Parameters.AddWithValue("@noPanels", noPanels);
                        cmd.Parameters.AddWithValue("@title", title);
                        cmd.Parameters.AddWithValue("@altText", altText);
                        cmd.Parameters.AddWithValue("@publishDate", publishDate);
                        cmd.Parameters.AddWithValue("@comment", comment);
                        cmd.Parameters.AddWithValue("@imageType", imageType);
                        cmd.Connection = _myConn;
                        cmd.ExecuteNonQuery();
                    }
                    _myConn.Close();
                }
                result = true;

            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }

        public bool Delete(int? comicNo)
        {
            bool result = false;

            try
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    string sql = "delete from comics where comicNo= @comicNo";
                    cmd.CommandText = sql;
                    cmd.Parameters.AddWithValue("@comicNo", comicNo);
                    cmd.Connection = _myConn;
                    cmd.ExecuteNonQuery();
                }
                    
                result = true;
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }
    }
}